package com.zmn.oms.third.jingdong;

import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.third.jingdong.dto.JingdongAccessToken;
import com.zmn.oms.third.jingdong.service.JingdongTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/09/03 16:08
 */
@Slf4j
public class JingdongTokenManager {
    private static String TOKEN;// = "a458157fa3b744069ac09716ae022e07";
    private static String REFRESH_TOKEN;// = "a78243274ccf4c9eb47ce04d6180372c";

    /**
     * 获取token
     * @return
     */
    public static String getToken() {
        if (StringUtils.isNotBlank(TOKEN)) {
            return TOKEN;
        }

        JingdongTokenService jingdongTokenService = SpringBeanFactoryUtil.getBean("jingdongTokenService");
        JingdongAccessToken token = jingdongTokenService.getToken();
        if (token != null) {
            TOKEN = token.getAccessToken();
            log.info("【{}】<queryAccessToken> AccessToken:[{}]", JingdongConsts.CHANNEL_NAME, token.toString());
        } else {
            log.info("【{}】<queryAccessToken> 查找失败。", JingdongConsts.CHANNEL_NAME);
        }

        return TOKEN;
    }

    /**
     * 获取refreshToken
     * @return
     */
    public static String getRefreshToken() {
        if (StringUtils.isNotBlank(REFRESH_TOKEN)) {
            return REFRESH_TOKEN;
        }

        JingdongTokenService jingdongTokenService = SpringBeanFactoryUtil.getBean("jingdongTokenService");
        JingdongAccessToken token = jingdongTokenService.getToken();
        if (token != null) {
            REFRESH_TOKEN = token.getRefreshToken();
            log.info("【{}】<queryAccessToken> AccessToken:[{}]", JingdongConsts.CHANNEL_NAME, token.toString());
        } else {
            log.info("【{}】<queryAccessToken> 查找失败。", JingdongConsts.CHANNEL_NAME);
        }

        return REFRESH_TOKEN;
    }

    /**
     * 设置token
     * @param token
     */
    public synchronized static void setToken(JingdongAccessToken token) {
        JingdongTokenService jingdongTokenService = SpringBeanFactoryUtil.getBean("jingdongTokenService");

        if (token != null && StringUtils.isNotBlank(token.getAccessToken())) {
            TOKEN = token.getAccessToken();
            REFRESH_TOKEN = token.getRefreshToken();
        }

        boolean isSuccess = false;
        try {
            isSuccess = jingdongTokenService.saveToken(token);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (isSuccess) {
            log.info("【{}】<saveAccessToken> 保存成功。", JingdongConsts.CHANNEL_NAME);
        } else {
            log.info("【{}】<saveAccessToken> 保存失败。", JingdongConsts.CHANNEL_NAME);
        }
    }

}
